import {
  Message
} from 'element-ui';

let doc = document;
let toString = Object.prototype.toString;

function countHeight(el, defHeight) {
  let t = doc.body.clientHeight - el.getBoundingClientRect().top - defHeight;
  return t < 300 ? 300 : t;
}

function autoHeight(that, el, dh = 68) {
  that.$nextTick(function () {
    that.st = that.$util.countHeight(el, dh);
    window.onresize = function () {
      that.st = that.$util.countHeight(el, dh);
    };
  });
}

function setAttr(t, o) {
  for (let i in o) {
    t[i] = o[i];
  }
}

function locals(o) {
  for (let i in o) {
    localStorage.setItem(i, o[i]);
  }
}

function toast({
  message = '操作成功',
  type = 'success',
  showClose = false,
  center = false
}) {
  Message({
    message,
    type,
    showClose,
    center
  });
}

function confirm({
  that,
  content = '确定执行该操作',
  title = '提示',
  confirmButtonText = '确定',
  cancelButtonText = '取消',
  type = 'warning',
  cancelType = 'info',
  cancelMsg = '已取消'
}) {
  return new Promise((resolve) => {
    that
      .$confirm(content, title, {
        confirmButtonText: confirmButtonText,
        cancelButtonText: cancelButtonText,
        type: type
      })
      .then(() => {
        resolve(true);
      })
      .catch(() => {
        resolve(false);
        that.$message({
          type: cancelType,
          message: cancelMsg
        });
      });
  });
}

function ext(o, p) {
  for (let i in p) {
    o[i] = p[i];
  }
  return o;
}

function ext2(o, p) {
  o = JSON.parse(JSON.stringify(o));
  for (let i in p) {
    if (!!o.hasOwnProperty(i)) {
      o[i] = p[i];
    }
  }
  return o;
}

/**
 * 是否推广员
 * @returns {boolean}
 */
function checkSupplier() {
  if (localStorage.getItem('userType') == 2) {
    return true;
  } else {
    return false;
  }
}

/**
 * 是否存在权限
 * @returns {boolean}
 */
function checkAuth(auth) {
  if (auth === '') {
    return false;
  }

  if (localStorage.getItem('autoButton') && !(localStorage.getItem('autoButton').split(',').indexOf(auth) > -1)) {
    return false;
  }

  return true;
}

/**
 * 获取菜单
 * @param routes
 * @returns {[]}
 */
function getMenuTree(menuList, routes) {
  //权限路由
  let authRoutes = [];

  //数组处理
  function handleMenuList(menuList, routes) {
    menuList.filter((item, i) => {
      let temp = routes.find((ri) => ri.path == item.web_path);
      // console.log(temp)

      if (temp) {
        let localAuth = {
          name: temp.name,
          meta: {
            title: item.title,
            icon: item.icon
          },
          path: temp.path,
          component: temp.component,
          id: item.id,
          pid: item.pid,
          alwaysShow: temp.alwaysShow ? true : false
        };
        if (temp.redirect) localAuth.redirect = temp.redirect;

        authRoutes.push(localAuth);

        if (item.child) {
          handleMenuList(item.child, temp.children, localAuth);
        }
      }
    });

    return parent;
  }

  handleMenuList(menuList, routes);

  //组装树
  function toTree(data) {
    let result = [];
    if (!Array.isArray(data)) {
      return result;
    }
    data.forEach((item) => {
      delete item.children;
    });
    let map = {};
    data.forEach((item) => {
      map[item.id] = item;
    });
    data.forEach((item) => {
      let parent = map[item.pid];
      if (parent) {
        (parent.children || (parent.children = [])).push(item);
      } else {
        result.push(item);
      }
    });
    return result;
  }

  // console.log(authRoutes)

  let authRoutesTree = toTree(authRoutes);

  // console.log(authRoutesTree)

  return authRoutesTree;
}

function region(arr) {
  let r = [];
  arr.forEach((cur, i) => {
    r[i] = [];
    cur += '';
    r[i][0] = (cur.slice(0, 2) + '0000') * 1;
    r[i][1] = (cur.slice(0, 4) + '00') * 1;
    r[i][2] = cur * 1;
  });
  return r;
}

function setOwnAttr(o, n) {
  let cur = '';
  for (let i in o) {
    cur = n[i];
    if (cur) {
      o[i] = cur;
    }
  }
}

function isNumber(n, t) {
  const nn = n;
  n *= 1;
  let tt = isNaN(n) ? false : toString.call(n) === '[object Number]';
  if (!tt) {
    return false;
  }
  if (!!t) {
    if (nn.indexOf('.') > -1) {
      return false;
    }
    return /(^[1-9]\d*$)/.test(n);
  }
  return true;
}

// 校验手机号
function checkPhone(p) {
  return /^1[3456789]\d{9}$/.test(p);
}

function ctx(d, def = []) {
  if (!d) {
    return def;
  }
  if (toString.call(def) === '[object Object]') {
    return toString.call(d) === '[object Object]' ? d : {};
  }
  return d;
}

async function regionData(that, v = 3) {
  let l = ['', 'commonRegion:country1:level:1', '', 'commonRegion:level:3'],
    k = l[v],
    region = localStorage.getItem(k),
    o = ['', {
      country: 1,
      level: 1
    }, '', {
      level: 3
    }];
  if (region != null) {
    return JSON.parse(region);
  } else {
    const {
      result
    } = await that.$.util.commonRegion(o[v]);
    localStorage.setItem(k, JSON.stringify(result));
    return result;
  }
}

/**
 * 获取系统配置信息
 * @param that
 * @param k
 * @returns {Promise<string|*>}
 */
async function system(that, k) {
  let kv = localStorage.getItem(k);
  if (!!kv) {
    return kv;
  } else {
    const {
      result
    } = await that.$.util.system();
    locals(result);
    return result[k];
  }
}

/**
 * 清空系统配置信息
 * @param that
 * @param k
 * @returns {Promise<string|*>}
 */
async function clearSystem(that, k) {
  localStorage.removeItem(k);
}

export default {
  toString,
  countHeight,
  autoHeight,
  setAttr,
  locals,
  setOwnAttr,
  toast,
  confirm,

  ext,
  ext2,

  checkSupplier,
  checkAuth,
  getMenuTree,
  region,
  isNumber,
  checkPhone,

  ctx,
  regionData,
  system,
  clearSystem
};
